<template>
  <el-drawer v-model="dialogVisible" title="团购赠品">
    <div class="flex flex-row justify-between mb-2">
      <el-button plain type="primary" @click="openForm()" v-hasRole="['shop_admin']">
        <Icon class="mr-5px" icon="ep:plus" />
        加入赠品
      </el-button>
      <el-button @click="loadTableData">
        <Icon class="mr-5px" icon="ep:refresh" />
        刷新赠品
      </el-button>
    </div>
    <ContentWrap>
      <el-card class="box-card !border-none" shadow="never">
        <div class="mt-[5px]">
          <el-table :data="tableData.list" size="large" v-loading="tableData.loading">
            <template #empty>
              <span class="text-red-500">{{ !tableData.loading ? '请先加入赠品' : '' }}</span>
            </template>
            <el-table-column label="赠品信息" min-width="180">
              <template #default="{ row }">
                <p>{{ row.name }}</p>
                <p class="text-sm text-gray-500">{{ row.note }}</p>
              </template>
            </el-table-column>
            <el-table-column label="所属店铺" min-width="120">
              <template #default="{ row }">
                <div class="flex flex-col items-start justify-start">
                  <img
                    class="w-[50px] h-[50px] mr-[10px] border border-solid border-gray-50"
                    :src="row.shop?.logo || '/placeholder.png'"
                    alt=""
                  />
                  <span>{{ row.shop?.name || '未知' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="领取限制" min-width="150">
              <template #default="{ row }">
                <div class="flex flex-row items-center">
                  <el-tag type="primary">{{ row.typeName }}</el-tag>
                  <div v-if="row.price > 0" class="ml-5px"
                    >含成本 <span class="text-orange-500">¥{{ fenToYuan(row.price) }}</span></div
                  >
                  <span v-else class="ml-5px text-green-500">免费</span>
                </div>
                <p>每人限领 {{ row.takeLimitCount }} {{ row.unit }}</p>
              </template>
            </el-table-column>
            <el-table-column label="生效时间" align="center" prop="startTime" min-width="170">
              <template #default="{ row }">
                <el-tag v-if="row.valid" type="success">已生效</el-tag>
                <el-tag v-if="!row.valid && !row.invalid" type="warning">待生效</el-tag>
                <br />
                <span class="ml-5px">{{ formatTime(row.startTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="作废时间" align="center" min-width="170">
              <template #default="{ row }">
                <el-tag v-if="row.invalid" type="warning">已作废</el-tag>
                <el-tag v-else type="success">待作废</el-tag>
                <br />
                <span class="ml-5px">{{ formatTime(row.endTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-hasRole="['shop_admin']"
              label="操作"
              min-width="100"
              align="center"
              fixed="right"
            >
              <template #default="scope">
                <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </ContentWrap>

    <GiftSelect ref="formRef" @change="handleGiftSelect" />
  </el-drawer>
</template>

<script lang="ts" setup name="GrouponGift">
import * as GiftActivityApi from '@/api/mall/promotion/gift/activity'
import * as GrouponPackageApi from '@/api/mall/promotion/groupon/package'
import { fenToYuan, formatTime } from '@/utils'
import GiftSelect from '@/views/mall/promotion/gift/GiftSelect.vue'

const message = useMessage()

const emit = defineEmits(['refresh'])

const dialogVisible = ref(false)
const grouponPackageId = ref<number | string>('0')

const tableData = reactive({
  loading: true,
  list: [],
  searchParam: {}
})

const loadTableData = async () => {
  tableData.loading = true
  const grouponPackage = await GrouponPackageApi.getDetailById(grouponPackageId.value)
  GiftActivityApi.getListByIds(grouponPackage.giftActivityIds)
    .then((res: any) => {
      tableData.loading = false
      tableData.list = res
    })
    .catch(() => {
      tableData.loading = false
    })
}

const handleGiftSelect = async (e: any[]) => {
  //console.log(JSON.stringify(e))
  if (!e?.length) {
    message.error('请选择赠品')
    return
  }
  try {
    const giftActivityIds: any = []
    for (let giftActivity of e) {
      giftActivityIds.push(giftActivity.id)
    }
    await GrouponPackageApi.addGifts(grouponPackageId.value, giftActivityIds)
    message.success('加入赠品成功')
    loadTableData()
    emit('refresh')
  } catch {}
}

const open = (packageId: number | string) => {
  dialogVisible.value = true
  grouponPackageId.value = packageId
  loadTableData()
}
defineExpose({
  open
})

const formRef = ref()
const openForm = () => {
  formRef.value.open()
}

const handleDelete = async (giftActivityId: number | string) => {
  try {
    await message.delConfirm()
    await GrouponPackageApi.removeGift(grouponPackageId.value, giftActivityId)
    message.success('移除赠品成功')
    loadTableData()
    emit('refresh')
  } catch {}
}
</script>
